<template>
  <div class="weather-page big-screen" :class="backdropClass">
    <el-card class="glass" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="title-left">
            <span class="title">城市天气大屏</span>
            <span class="subtitle">{{ weather?.provinceCity || '-' }}</span>
          </div>
          <div class="title-right">{{ nowText }}</div>
        </div>
      </template>

      <div class="controls">
        <el-form :inline="true" label-width="90px">
          <el-form-item label="城市">
            <el-input :value="weather?.provinceCity || '-'" readonly style="width:260px" />
          </el-form-item>
        </el-form>
      </div>

      <div class="screen-grid">
        <div class="left-panel">
          <div class="hero">
            <div class="icon">{{ weatherIcon }}</div>
            <div class="temp">{{ temperatureText }}</div>
            <div class="weather-text">{{ weatherText }}</div>
          </div>
          <div class="stats">
            <div class="stat">
              <div class="label">湿度</div>
              <div class="value">{{ humidityText }}</div>
            </div>
            <div class="stat">
              <div class="label">风向/风力</div>
              <div class="value">{{ windText }}</div>
            </div>
            <div class="stat">
              <div class="label">更新时间</div>
              <div class="value">{{ updateText }}</div>
            </div>
            <div class="stat">
              <div class="label">城市</div>
              <div class="value">{{ weather?.provinceCity || '-' }}</div>
            </div>
          </div>
        </div>
        <div class="right-panel">
          <div id="amap-container" class="map"></div>
        </div>
      </div>
      <el-empty v-if="!weather && !loading" description="点击地图以查询天气" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getReadClient } from '@/Urls/AxiosHelper'

const query = ref({ lng: '', lat: '', adcode: '' })
const loading = ref(false)
const weather = ref<any>(null)
const amapKey = ref<string>('eb702178680854c0804d16a24cfc5071')
const mapLoading = ref(false)
let map:any = null
let marker:any = null

const coordText = computed(()=> query.value.lng && query.value.lat ? `${query.value.lng}, ${query.value.lat}` : '')
// 固定使用 AxiosHelper 的"读"索引 1
const read = getReadClient(1)
const baseUrl = computed(()=> (read as any)?.defaults?.baseURL || '')
// 实时更新的时间
const nowText = ref(new Date().toLocaleString())
let timeTimer: number | null = null
const weatherText = computed(()=> String(weather.value?.text || weather.value?.weather || '-'))
const temperatureText = computed(()=> weather.value?.temp ? `${weather.value?.temp}°C` : (weather.value?.temperature ? `${weather.value?.temperature}°C` : '--'))
const humidityText = computed(()=> weather.value?.humidity!=null ? `${weather.value?.humidity} %` : '--')
const windText = computed(()=> {
  const dir = weather.value?.windDir || weather.value?.winddirection || '-'
  const pow = weather.value?.windSpeed || weather.value?.windpower || '-'
  return `${dir} / ${pow}`
})
const updateText = computed(()=> weather.value?.obsTime || weather.value?.reporttime || weather.value?.updateTime || '-')
const weatherIcon = computed(()=>{
  const t = weatherText.value
  if(/雷/.test(t)) return '⛈️'
  if(/雨/.test(t)) return '🌧️'
  if(/雪/.test(t)) return '❄️'
  if(/多云|阴/.test(t)) return '⛅'
  if(/雾|霾|沙/.test(t)) return '🌫️'
  return '☀️'
})
const backdropClass = computed(()=>{
  const t = weatherText.value
  if(/雷|暴雨/.test(t)) return 'bg-storm'
  if(/雨/.test(t)) return 'bg-rain'
  if(/雪/.test(t)) return 'bg-snow'
  if(/多云|阴/.test(t)) return 'bg-cloud'
  if(/雾|霾|沙/.test(t)) return 'bg-fog'
  return 'bg-sunny'
})

function useSaved(){
  const lng = localStorage.getItem('gaode_lng') || ''
  const lat = localStorage.getItem('gaode_lat') || ''
  if(lng && lat){ query.value = { ...query.value, lng, lat } }
}
function saveCurrent(){
  if(query.value.lng) localStorage.setItem('gaode_lng', query.value.lng)
  if(query.value.lat) localStorage.setItem('gaode_lat', query.value.lat)
  if(query.value.adcode) localStorage.setItem('gaode_adcode', query.value.adcode)
}

function saveAmapKey(){
  if(amapKey.value){
    localStorage.setItem('amap_js_key', amapKey.value)
    ElMessage.success('已保存 AMap Key')
  }
}

function loadKeyFromStorage(){
  // 优先使用固定的AMap Key，如果localStorage中有值则使用localStorage中的值
  const k = localStorage.getItem('amap_js_key') || 'eb702178680854c0804d16a24cfc5071'
  amapKey.value = k
}

function loadAMapScript(key:string){
  return new Promise<void>((resolve, reject)=>{
    if((window as any).AMap){ resolve(); return }
    const src = `https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(key)}`
    const s = document.createElement('script')
    s.type = 'text/javascript'
    s.src = src
    s.onload = ()=> resolve()
    s.onerror = ()=> reject(new Error('AMap 脚本加载失败'))
    document.head.appendChild(s)
  })
}

async function ensureMap(){
  if(map){ return }
  const key = amapKey.value || localStorage.getItem('amap_js_key') || ''
  if(!key){ ElMessage.warning('请先填写并保存 AMap Key'); return }
  mapLoading.value = true
  try{
    await loadAMapScript(key)
    initMap()
  }catch(e:any){
    ElMessage.error(e?.message || '地图初始化失败')
  }finally{
    mapLoading.value = false
  }
}

function initMap(){
  // @ts-ignore
  const AMap = (window as any).AMap
  if(!AMap){ return }
  map = new AMap.Map('amap-container', {
    zoom: 11,
    viewMode: '2D',
    center: query.value.lng && query.value.lat ? [Number(query.value.lng), Number(query.value.lat)] : undefined,
  })
  map.on('click', (e:any)=>{
    const lng = e?.lnglat?.lng
    const lat = e?.lnglat?.lat
    if(lng!=null && lat!=null){
      setMarker(lng, lat)
      query.value = { ...query.value, lng: String(lng), lat: String(lat) }
      reverseGeocodeAndFetch(lng, lat)
    }
  })
  try{
    // @ts-ignore
    AMap.plugin('AMap.Geolocation', function(){
      // @ts-ignore
      const geo = new AMap.Geolocation({ enableHighAccuracy: true, timeout: 5000 })
      geo.getCurrentPosition((status:string, result:any)=>{
        if(status==='complete' && result?.position){
          const p = result.position
          setMarker(p.lng, p.lat)
          query.value = { ...query.value, lng: String(p.lng), lat: String(p.lat) }
          reverseGeocodeAndFetch(p.lng, p.lat)
        }
      })
    })
  }catch{}
}

function setMarker(lng:number, lat:number){
  // @ts-ignore
  const AMap = (window as any).AMap
  if(!AMap || !map) return
  if(!marker){
    // @ts-ignore
    marker = new AMap.Marker({ position: [lng, lat] })
    map.add(marker)
  }else{
    marker.setPosition([lng, lat])
  }
  map.setCenter([lng, lat])
}

function reverseGeocodeAndFetch(lng:number, lat:number){
  // @ts-ignore
  const AMap = (window as any).AMap
  if(!AMap){ fetchWeather(); return }
  try{
    // @ts-ignore
    AMap.plugin('AMap.Geocoder', function(){
      // @ts-ignore
      const geocoder = new AMap.Geocoder()
      geocoder.getAddress([lng, lat], (status:string, result:any)=>{
        if(status==='complete' && result?.regeocode){
          const adcode = result?.regeocode?.addressComponent?.adcode || ''
          const province = result?.regeocode?.addressComponent?.province || ''
          const city = result?.regeocode?.addressComponent?.city || ''
          query.value.adcode = String(adcode || '')
          const provinceCity = `${province}${city ? ' ' + city : ''}`
          weather.value = { ...(weather.value||{}), provinceCity }
        }
        saveCurrent()
        fetchWeather()
      })
    })
  }catch{
    saveCurrent()
    fetchWeather()
  }
}

async function requestWeather(path:string){
  const lng = query.value.lng
  const lat = query.value.lat
  const adcode = query.value.adcode
  // 后端需要三个参数：lng、lat、adcode（同时附带 longitude/latitude 兼容）
  const params:any = { lng, lat, adcode, longitude: lng, latitude: lat, city: adcode }
  return await read.get(path, { params })
}

async function fetchWeather(){
  if(!query.value.lng || !query.value.lat){ return }
  loading.value = true
  weather.value = null
  try{
    let res
    const tryPaths = [
      'schedread/api/Weather/location',
      'schedread/api/Weather/location',
      'schedread/api/Weather/location',
      'schedread/api/Weather/location',
      'schedread/api/Weather/location'
    ]
    const tryIndexes = [1,0,2,3,4]
    let lastErr:any = null
    outer: for(const p of tryPaths){
      for(const idx of tryIndexes){
        try{
          const cli = getReadClient(idx)
          res = await cli.get(p, { params: { lng: query.value.lng, lat: query.value.lat, adcode: query.value.adcode, longitude: query.value.lng, latitude: query.value.lat, city: query.value.adcode } })
          if(res?.status>=200 && res?.status<300){ break outer }
        }catch(e:any){ lastErr = e; continue }
      }
    }
    if(!res){ throw lastErr || new Error('接口不可达') }
    const raw = res?.data
    // 兼容你的返回结构：{ status, lives:[{...}] }
    const live = raw?.lives?.[0]
    const normalized = live ? {
      provinceCity: `${live?.province || ''}${live?.city ? ' ' + live.city : ''}`.trim(),
      weather: live?.weather,
      temperature: live?.temperature,
      humidity: live?.humidity,
      windDir: live?.winddirection,
      windSpeed: live?.windpower,
      reporttime: live?.reporttime,
      adcode: live?.adcode,
    } : (raw?.data ?? raw ?? null)
    weather.value = normalized
    if(!normalized){ ElMessage.info('未获取到天气数据') }
  }catch(e:any){
    ElMessage.error(e?.message || '获取天气失败')
  }finally{
    loading.value = false
  }
}

// 更新时间显示
function updateTime() {
  nowText.value = new Date().toLocaleString()
}

onMounted(()=>{
  loadKeyFromStorage()
  useSaved()
  ensureMap()
  // 启动时间更新定时器
  timeTimer = setInterval(updateTime, 1000)
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timeTimer) {
    clearInterval(timeTimer)
    timeTimer = null
  }
})
</script>

<style scoped>
.weather-page{ padding: 0; min-height: calc(100vh - 24px); }
.big-screen{ position: relative; }
.glass{ background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.18); backdrop-filter: blur(10px); }
.card-header{ display:flex; align-items:center; justify-content:space-between; font-weight: 600; }
.card-header .title{ font-size: 22px; margin-right: 12px; }
.card-header .subtitle{ font-size: 14px; opacity: 0.85; }
.controls{ margin-bottom: 8px; }
.screen-grid{ display:grid; grid-template-columns: 1fr 1.2fr; gap: 12px; align-items: stretch; }
.left-panel{ display:flex; flex-direction:column; gap: 12px; }
.hero{ display:flex; align-items:center; gap: 16px; padding: 16px; border-radius: 12px; background: rgba(255,255,255,0.12); }
.hero .icon{ font-size: 56px; }
.hero .temp{ font-size: 48px; font-weight: 700; }
.hero .weather-text{ font-size: 20px; opacity: 0.9; }
.stats{ display:grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
.stat{ padding: 12px; border-radius: 12px; background: rgba(255,255,255,0.08); }
.stat .label{ font-size: 12px; opacity: 0.8; }
.stat .value{ font-size: 18px; font-weight: 600; margin-top: 6px; }
.right-panel{ }
.map{ width: 100%; height: 520px; border-radius: 12px; overflow: hidden; border: 1px solid rgba(255,255,255,0.2); }

/* 背景主题 */
.bg-sunny{ background: linear-gradient(135deg, #74b9ff 0%, #a29bfe 100%); }
.bg-cloud{ background: linear-gradient(135deg, #bdc3c7 0%, #2c3e50 100%); }
.bg-rain{ background: linear-gradient(135deg, #4b79a1 0%, #283e51 100%); }
.bg-snow{ background: linear-gradient(135deg, #e0eafc 0%, #cfdef3 100%); }
.bg-storm{ background: linear-gradient(135deg, #232526 0%, #414345 100%); }
.bg-fog{ background: linear-gradient(135deg, #757f9a 0%, #d7dde8 100%); }
</style>


